import { fabric } from 'fabric'
import { ref } from 'vue'

export function useSelection(getCanvas) {
  const selectionMode = ref('rect') // rect, magic-wand, lasso
  const tolerance = ref(32) // 魔棒工具的容差值
  let isSelecting = false
  let selectionPath = []

  // 开始矩形选区
  const startRectSelection = () => {
    const fabricCanvas = getCanvas()
    if (!fabricCanvas) return

    // 禁用对象选择，启用选区模式
    fabricCanvas.selection = true
    fabricCanvas.getObjects().forEach(obj => {
      obj.selectable = false
      obj.evented = false
    })

    // 创建选区矩形
    fabricCanvas.on('mouse:down', onMouseDown)
    fabricCanvas.on('mouse:move', onMouseMove)
    fabricCanvas.on('mouse:up', onMouseUp)
  }

  // 开始套索选区
  const startLassoSelection = () => {
    const fabricCanvas = getCanvas()
    if (!fabricCanvas) return

    fabricCanvas.isDrawingMode = true
    fabricCanvas.freeDrawingBrush = new fabric.PencilBrush(fabricCanvas)
    fabricCanvas.freeDrawingBrush.color = 'rgba(0,0,0,0.3)'
    fabricCanvas.freeDrawingBrush.width = 1

    fabricCanvas.on('path:created', onLassoComplete)
  }

  // 魔棒选区
  const startMagicWandSelection = (x, y) => {
    const fabricCanvas = getCanvas()
    if (!fabricCanvas) return

    const ctx = fabricCanvas.getContext('2d')
    const imageData = ctx.getImageData(0, 0, fabricCanvas.width, fabricCanvas.height)
    const pixels = imageData.data
    const width = imageData.width
    const height = imageData.height

    // 获取点击位置的颜色
    const pos = (y * width + x) * 4
    const targetR = pixels[pos]
    const targetG = pixels[pos + 1]
    const targetB = pixels[pos + 2]
    const targetA = pixels[pos + 3]

    // 创建访问标记数组
    const visited = new Array(width * height).fill(false)
    const selected = []

    // 广度优先搜索相似颜色的像素
    const queue = [[x, y]]
    visited[y * width + x] = true
    selected.push([x, y])

    while (queue.length > 0) {
      const [curX, curY] = queue.shift()
      const neighbors = [
        [curX + 1, curY],
        [curX - 1, curY],
        [curX, curY + 1],
        [curX, curY - 1]
      ]

      for (const [nx, ny] of neighbors) {
        if (
          nx >= 0 && nx < width &&
          ny >= 0 && ny < height &&
          !visited[ny * width + nx]
        ) {
          const pos = (ny * width + nx) * 4
          const r = pixels[pos]
          const g = pixels[pos + 1]
          const b = pixels[pos + 2]
          const a = pixels[pos + 3]

          // 计算颜色差异
          const colorDiff = Math.sqrt(
            Math.pow(r - targetR, 2) +
            Math.pow(g - targetG, 2) +
            Math.pow(b - targetB, 2) +
            Math.pow(a - targetA, 2)
          )

          if (colorDiff <= tolerance.value) {
            queue.push([nx, ny])
            visited[ny * width + nx] = true
            selected.push([nx, ny])
          }
        }
      }
    }

    // 创建选区路径
    const path = new fabric.Path(createSelectionPath(selected), {
      fill: 'rgba(0,0,0,0.3)',
      stroke: '#fff',
      strokeWidth: 1,
      selectable: false,
      evented: false
    })

    fabricCanvas.add(path)
    fabricCanvas.renderAll()
  }

  // 辅助函数：创建选区路径
  const createSelectionPath = (points) => {
    if (points.length === 0) return ''

    let path = `M ${points[0][0]} ${points[0][1]}`
    for (let i = 1; i < points.length; i++) {
      path += ` L ${points[i][0]} ${points[i][1]}`
    }
    path += ' Z'
    return path
  }

  // 清除选区
  const clearSelection = () => {
    const fabricCanvas = getCanvas()
    if (!fabricCanvas) return

    // 移除所有选区路径
    fabricCanvas.getObjects().forEach(obj => {
      if (obj.type === 'path' && !obj.evented) {
        fabricCanvas.remove(obj)
      }
    })

    // 重置选择模式
    fabricCanvas.selection = false
    fabricCanvas.isDrawingMode = false
    fabricCanvas.getObjects().forEach(obj => {
      obj.selectable = true
      obj.evented = true
    })

    // 移除事件监听
    fabricCanvas.off('mouse:down', onMouseDown)
    fabricCanvas.off('mouse:move', onMouseMove)
    fabricCanvas.off('mouse:up', onMouseUp)
    fabricCanvas.off('path:created', onLassoComplete)

    fabricCanvas.renderAll()
  }

  // 鼠标事件处理函数
  const onMouseDown = (e) => {
    isSelecting = true
    selectionPath = [e.pointer]
  }

  const onMouseMove = (e) => {
    if (!isSelecting) return
    selectionPath.push(e.pointer)
  }

  const onMouseUp = () => {
    if (!isSelecting) return
    isSelecting = false

    const fabricCanvas = getCanvas()
    if (!fabricCanvas) return

    // 创建选区路径
    const path = new fabric.Path(createSelectionPath(selectionPath), {
      fill: 'rgba(0,0,0,0.3)',
      stroke: '#fff',
      strokeWidth: 1,
      selectable: false,
      evented: false
    })

    fabricCanvas.add(path)
    fabricCanvas.renderAll()
  }

  const onLassoComplete = (e) => {
    const fabricCanvas = getCanvas()
    if (!fabricCanvas) return

    const path = e.path
    path.set({
      fill: 'rgba(0,0,0,0.3)',
      stroke: '#fff',
      strokeWidth: 1,
      selectable: false,
      evented: false
    })

    fabricCanvas.renderAll()
  }

  return {
    selectionMode,
    tolerance,
    startRectSelection,
    startLassoSelection,
    startMagicWandSelection,
    clearSelection
  }
} 